package com.chapter07.dao;

import com.bdqn.util.JDBCUtils;
import com.pojo.Customers;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class CustomersDaoMySQLImpl extends BaseDao<Customers> implements CustomersDao {
    @Override
    public int insert(Connection connection, Customers customers) throws SQLException {
        String sql = "INSERT INTO `customers` (`name`,`email`,`birth`) VALUES (?,?,?)";
        int i = update(connection, sql,
                customers.getName(),
                customers.getEmail(),
                customers.getBirth());

//        PreparedStatement preparedStatement = connection.prepareStatement(sql);
//        preparedStatement.setObject(1, );
//        preparedStatement.setObject(2, );
//        preparedStatement.setObject(3, );
//        int i = preparedStatement.executeUpdate();
        return i;
    }

    @Override
    public int deleteById(Connection connection, int id) throws SQLException {
        String sql = "DELETE FROM `customers` WHERE id = ?";
        int i = update(connection, sql, id);
//        PreparedStatement preparedStatement = connection.prepareStatement(sql);
//        preparedStatement.setObject(1, id);
//        int i = preparedStatement.executeUpdate();
//        if (i > 0) {
//            System.out.println("成功");
//        }
        return i;
    }

    @Override
    public void update(Connection connection, Customers customers) throws SQLException {
        String sql = "UPDATE `customers` SET `name` = ? WHERE id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setObject(1, customers.getName());
        preparedStatement.setObject(2, customers.getId());
        int i = preparedStatement.executeUpdate();
        if (i > 0) {
            System.out.println("成功");
        }
    }

    @Override
    public List<Customers> getAll(Connection connection) {
        String sql = "SELECT * FROM customers;";
        return query(connection, sql);
    }

    @Override
    public Customers getCustomersById(Connection connection, int id) throws InstantiationException, IllegalAccessException {
        String sql = "SELECT * FROM customers WHERE id = ?;";
        return getSingletonEntity(connection, sql, id);
    }
}
